package domain.match;

import game.GameModel;
import game.clicker.Clicker;

import java.io.Serializable;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;

import application.config.Config;
import application.config.Config.Status;
import domain.tournament.ITournamentStyle;
import domain.users.User;

public class GameMatch extends Observable implements IGameMatch, Serializable {

	private static final long serialVersionUID = 4252941889638419266L;
	private String title;
	private Date creationDate;
	private transient ServerSocket serverSocket;
	private List<User> players;
	private GameModel game;
	private int gameMatchID;

	public GameMatch(int gameMatchID, String title, int port) {
		this.title = title;
		this.creationDate = new Date();
		this.players = new ArrayList<User>();
		this.game = new Clicker();
		this.gameMatchID = gameMatchID;
	}
	
	@Override
	public void startMatch() {
		game.setPlayers(players);
		game.startGame();
	}

	@Override
	public int getNumPlayers() {
		return players.size();
	}

	@Override
	public void addPlayer(User player) {
		players.add(player);
		addObserver(players.get(players.size() - 1));

		System.out.println("-- Notify new player object to the other player --");
		notifyClients(Config.Status.CLIENT_CONNECTED);
	}

	@Override
	public Iterator<User> getPlayers() {
		return players.iterator();
	}

	@Override
	public ServerSocket getServerSocket() {
		return serverSocket;
	}

	@Override
	public int getServerPort() {
		return Config.PROTOCOL_PORT;
	}

	@Override
	public ITournamentStyle getGameRules() {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	/** Notify the clients */
	private void notifyClients(Status status) {
		setChanged();
		notifyObservers(status);
	}

	@Override
	public String getTitle() {
		return title;
	}

	@Override
	public Date getCreationDate() {
		return creationDate;
	}

	@Override
	public String toString() {
		return title + " (players: " + players.size() + "/64)";
	}

	@Override
	public int getGameMatchID() {
		return gameMatchID;
	}
}
